import json

from odoo import http
from odoo.http import request
import logging

_logger = logging.getLogger(__name__)


class ProductController(http.Controller):

    @http.route('/api/products', type='http', auth='public', methods=['GET'])
    def get_products(self):
        base_url = request.env['ir.config_parameter'].sudo().get_param('web.base.url')

        # 获取URL参数中的id
        product_id = request.httprequest.args.get('id')
        if product_id:
            # 如果存在id参数，则重定向到/shop/{id}
            return request.redirect(f'{base_url}/shop/{product_id}')

        # 获取URL参数中的format
        response_format = request.httprequest.args.get('format', 'html').lower()
        _logger.info('Current database:%s' % request.env.cr.dbname)
        Product = request.env['product.product'].sudo()  # 使用超级用户权限
        PriceList = request.env['product.pricelist'].sudo()
        pricelist = PriceList.search([('name', '=', '美团价格')], limit=1)
        if not pricelist:
            raise ValueError("Price list '美团价格' not found")

        product_name = request.httprequest.args.get('product_name')
        if product_name:
            products = Product.search(
                [('is_published', '=', True), ('sale_ok', '=', True), ('name', 'ilike', product_name)])
        else:

            products = Product.search([('is_published', '=', True), ('sale_ok', '=', True)])
        product_data = []
        for product in products:
            price = pricelist._get_product_price(product, 1)
            product_data.append({
                '商品名': product.name,
                '库存': product.qty_available,
                '价格': price,
                '图片url': f'{base_url}/web/image/product.product/{product.id}/image_1024/',
                '商品链接': f'{base_url}/shop/{product.id}',
                '商品ID': product.id  # 添加商品ID
            })

        if response_format == 'json':
            # 返回JSON格式的数据
            return request.make_response(json.dumps(product_data),
                                         [('Content-Type', 'application/json; charset=utf-8')])
        else:
            # 返回HTML格式的数据
            html_content = '<html><body><ul>'
            for product in product_data:
                html_content += f'<li>商品ID: {product["商品ID"]}, 商品名: {product["商品名"]}, 库存: {product["库存"]}, 价格: {product["价格"]}, <img src="{product["图片url"]}" alt="Product Image"><br><a href="{product["商品链接"]}">查看商品</a></li>'
            html_content += '</ul></body></html>'
            return request.make_response(html_content, [('Content-Type', 'text/html; charset=utf-8')])
